package com.partyjoin.project.system.user.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Destination;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.partyjoin.common.utils.CardUtil;
import com.partyjoin.common.utils.StringUtils;
import com.partyjoin.common.utils.poi.ExcelUtil;
import com.partyjoin.common.utils.security.ShiroUtils;
import com.partyjoin.framework.aspectj.lang.annotation.Log;
import com.partyjoin.framework.aspectj.lang.constant.BusinessType;
import com.partyjoin.framework.web.controller.BaseController;
import com.partyjoin.framework.web.domain.AjaxResult;
import com.partyjoin.framework.web.page.TableDataInfo;
import com.partyjoin.project.module.proposer.domain.Proposer;
import com.partyjoin.project.module.proposer.service.IProposerService;
import com.partyjoin.project.system.post.domain.Post;
import com.partyjoin.project.system.post.service.IPostService;
import com.partyjoin.project.system.role.domain.Role;
import com.partyjoin.project.system.role.service.IRoleService;
import com.partyjoin.project.system.user.domain.User;
import com.partyjoin.project.system.user.service.IUserService;
import com.partyjoin.project.tool.activemq.Producer;

/**
 * 用户信息
 * 
 * @author partyjoin
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController
{
    private String prefix = "system/user";
	
    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPostService postService;
    
    @Autowired
    private IProposerService proposerService;

    
    /**
     * 获取需要进行发展积极分子的申请对象用于添加会议时下拉列表（已谈话，且递交入党申请书满6个月,已提交积极分子备案登记表和推优表）
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/selectProposerToActivist")
    @ResponseBody
    public Object selectProposerToActivist(@RequestParam(value="type") String type){

    	List<User> userList = userService.selectProposerToActivist(ShiroUtils.getUserDeptId());
    	List<Map<String, Object>> userLists = new ArrayList<Map<String, Object>>();
    	//为未通过下拉框添加一个无的选项
    	if(type.equals("fail")){
    		Map<String, Object> failInfo = new HashMap<String, Object>();
    		failInfo.put("id", "999");
    		failInfo.put("name", "无");
    		failInfo.put("idCardNo", "无");
    		userLists.add(failInfo);
    	}
    	for(User u : userList){
    		Map<String, Object> info = new HashMap<String, Object>();
    		info.put("id", u.getUserId());
    		info.put("name", u.getUserName());
    		info.put("idCardNo", u.getIdCardNo());
    		info.put("remark", u.getRemark());
    		userLists.add(info);
    	}
    	return userLists;
    }
    
    /**
     * 获取需要进行发展对象培养的积极分子用于添加会议时下拉列表
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/selectActivistToDevelopment")
    @ResponseBody
    public Object selectActivistToDevelopment(@RequestParam(value="type") String type){
    	List<User> userList = userService.selectActivistToDevelopment(ShiroUtils.getUserDeptId());
    	List<Map<String, Object>> userLists = new ArrayList<Map<String, Object>>();
    	//为未通过下拉框添加一个无的选项
    	if(type.equals("fail")){
    		Map<String, Object> failInfo = new HashMap<String, Object>();
    		failInfo.put("id", "999");
    		failInfo.put("name", "无");
    		userLists.add(failInfo);
    	}
    	for(User u : userList){
    		Map<String, Object> info = new HashMap<String, Object>();
    		info.put("id", u.getUserId());
    		info.put("name", u.getUserName());
    		info.put("idCardNo", u.getIdCardNo());
    		info.put("remark", u.getRemark());
    		userLists.add(info);
    	}
    	return userLists;
    }
    
    /**
     * 获取需要进行预备党员预审的发展对象用于添加会议时下拉列表
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/selectDevelopmentToExamine")
    @ResponseBody
    public Object selectDevelopmentToExamine(@RequestParam(value="type") String type){
    	List<User> userList = userService.selectDevelopmentToExamine(ShiroUtils.getUserDeptId());
    	List<Map<String, Object>> userLists = new ArrayList<Map<String, Object>>();
    	//为未通过下拉框添加一个无的选项
    	if(type.equals("fail")){
    		Map<String, Object> failInfo = new HashMap<String, Object>();
    		failInfo.put("id", "999");
    		failInfo.put("name", "无");
    		userLists.add(failInfo);
    	}
    	for(User u : userList){
    		Map<String, Object> info = new HashMap<String, Object>();
    		info.put("id", u.getUserId());
    		info.put("name", u.getUserName());
    		info.put("idCardNo", u.getIdCardNo());
    		info.put("remark", u.getRemark());
    		userLists.add(info);
    	}
    	return userLists;
    }
    
    /**
     * 获取需要进行预备党员培养的发展对象用于添加会议时下拉列表
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/selectDevelopmentToPrepare")
    @ResponseBody
    public Object selectDevelopmentToPrepare(@RequestParam(value="type") String type){
    	List<User> userList = userService.selectDevelopmentToPrepare(ShiroUtils.getUserDeptId());
    	List<Map<String, Object>> userLists = new ArrayList<Map<String, Object>>();
    	//为未通过下拉框添加一个无的选项
    	if(type.equals("fail")){
    		Map<String, Object> failInfo = new HashMap<String, Object>();
    		failInfo.put("id", "999");
    		failInfo.put("name", "无");
    		userLists.add(failInfo);
    	}
    	for(User u : userList){
    		Map<String, Object> info = new HashMap<String, Object>();
    		info.put("id", u.getUserId());
    		info.put("name", u.getUserName());
    		info.put("idCardNo", u.getIdCardNo());
    		info.put("remark", u.getRemark());
    		userLists.add(info);
    	}
    	return userLists;
    }
    
    /**
     * 获取需要进行正式党员培养的预备党员用于添加会议时下拉列表
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/selectPrepareToOfficial")
    @ResponseBody
    public Object selectPrepareToOfficial(@RequestParam(value="type") String type){
    	List<User> userList = userService.selectPrepareToOfficial(ShiroUtils.getUserDeptId());
    	List<Map<String, Object>> userLists = new ArrayList<Map<String, Object>>();
    	//为未通过下拉框添加一个无的选项
    	if(type.equals("fail")){
    		Map<String, Object> failInfo = new HashMap<String, Object>();
    		failInfo.put("id", "999");
    		failInfo.put("name", "无");
    		userLists.add(failInfo);
    	}
    	for(User u : userList){
    		Map<String, Object> info = new HashMap<String, Object>();
    		info.put("id", u.getUserId());
    		info.put("name", u.getUserName());
    		info.put("idCardNo", u.getIdCardNo());
    		info.put("remark", u.getRemark());
    		userLists.add(info);
    	}
    	return userLists;
    }
    
    
    /**
     * 打开用户注册界面
     * @return
     */
    @GetMapping("/register")
    public String openReg(){
    	return prefix + "/register";
    }
    
    /**
     * 打开账号申请管理列表
     * @return
     */
    @RequiresPermissions("system:user:proposer:view")
    @GetMapping("/proposer")
    public String openProposer(){
    	return prefix + "/proposer";
    }
    
    /**
     * 获取账号申请用户列表
     * @param user
     * @return
     * @throws Exception
     */
    @RequiresPermissions("system:user:proposer:list")
    @PostMapping("/proposer/list")
    @ResponseBody
    public TableDataInfo proposerList(User user) throws Exception{
    	startPage();
    	//根据登陆管理员部门编号获取部门内成员
    	user.setDeptId(ShiroUtils.getUserDeptId());
    	List<User> list = userService.selectProposerList(user);
    	for(User u : list){
    		u.setAge((Integer) CardUtil.getCarInfo(u.getIdCardNo()).get("age"));
    	}
    	return getDataTable(list);
    }
    
    /**
     * 账号激活
     */
    @PostMapping("/proposer/accept")
    @ResponseBody
    public AjaxResult proposerAccept(User user){
    	try {
			userService.proposerAccept(user.getUserId());
			User u = ShiroUtils.getUser();
			//为申请人创建资料库
			Proposer proposer = new Proposer();
			proposer.setUserId(user.getUserId());
			proposer.setCreateBy(u.getUserName());
			proposer.setCreateTime(new Date());
			proposer.setDelFlag("0");
			proposerService.insertProposer(proposer);
			return success();
		} catch (Exception e) {
			return error("账号激活失败，请联系网站管理员");
		}
    }
    
    /**
     * 账号驳回
     * @return
     */
    @PostMapping("/proposer/notAccept")
    @ResponseBody
    public AjaxResult proposerNotAccept(User user){
    	try {
			userService.proposerNotAccept(user.getUserId());
			return success();
		} catch (Exception e) {
			return error("账号驳回失败，请联系网站管理员");
		}
    }

    /**
     * 打开用户列表
     * @return
     */
    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/user";
    }
    
    /**
     * 打开党员管理界面
     * @return
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/member")
    public String member(){
    	return prefix + "/member";
    }
    
    /**
     * 获取党员列表信息
     * @param user
     * @return
     */
    @RequiresPermissions("system:user:view")
    @PostMapping("/member/list")
    @ResponseBody
    public TableDataInfo memberList(User user){
    	startPage();
    	//无部门条件筛选时
    	if(user.getDeptId() == null){
        	user.setDeptId(ShiroUtils.getUserDeptId());
    	}
    	List<User> list = userService.selectMemberList(user);
    	List<Role> roleList = new ArrayList<Role>();
    	for(User u : list){
    		roleList = roleService.selectRolesByUserId(u.getUserId());
			int i = 0;
			Long[] roles = new Long[10];
    		for(Role role : roleList){
    			if(role.isFlag()){
        			roles[i] = role.getRoleId();
        			i++;
    			}
    		}
    		u.setRoleIds(roles);
    	}
    	return getDataTable(list);
    }
    
    /**
     * 打开党员发展时间轴
     * @param user
     * @return
     */
    @RequiresPermissions("system:user:develop")
    @GetMapping("/develop/{userId}")
    public String develop(@PathVariable("userId") Long userId, Model model){

    	return prefix + "/develop";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(User user)
    {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", action = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(User user) throws Exception
    {
        try
        {
            List<User> list = userService.selectUserList(user);
            ExcelUtil<User> util = new ExcelUtil<User>(User.class);
            return util.exportExcel(list, "user");
        }
        catch (Exception e)
        {
            return error("导出Excel失败，请联系网站管理员！");
        }
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", action = BusinessType.UPDATE)
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, Model model)
    {
        User user = userService.selectUserById(userId);
        List<Role> roles = roleService.selectRolesByUserId(userId);
        List<Post> posts = postService.selectPostsByUserId(userId);
        model.addAttribute("roles", roles);
        model.addAttribute("posts", posts);
        model.addAttribute("user", user);
        return prefix + "/edit";
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", action = BusinessType.INSERT)
    @GetMapping("/add")
    public String add(Model model)
    {
        List<Role> roles = roleService.selectRoleAll();
        List<Post> posts = postService.selectPostAll();
        model.addAttribute("roles", roles);
        model.addAttribute("posts", posts);
        return prefix + "/add";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", action = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, Model model)
    {
        User user = userService.selectUserById(userId);
        model.addAttribute("user", user);
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", action = BusinessType.SAVE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwd(User user)
    {
        int rows = userService.resetUserPwd(user);
        if (rows > 0)
        {
            return success();
        }
        return error();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", action = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        try
        {
            userService.deleteUserByIds(ids);
            return success();
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 保存用户
     * @throws Exception 
     * @throws NumberFormatException 
     */
    @RequiresPermissions("system:user:save")
    @Log(title = "用户管理", action = BusinessType.SAVE)
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult save(User user) throws NumberFormatException, Exception
    {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId()))
        {
            return error("不允许修改超级管理员用户");
        }
        //系统管理员添加用户不必输入身份证
        if(user.getIdCardNo() != null){
            user.setAge((Integer) (CardUtil.getCarInfo(user.getIdCardNo()).get("age")));
        }
        return userService.saveUser(user) > 0 ? success() : error();
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult register(User user){
    	return userService.register(user) > 0 ? success() : error();
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(User user)
    {
        String uniqueFlag = "0";
        if (user != null)
        {
            uniqueFlag = userService.checkLoginNameUnique(user.getLoginName());
        }
        return uniqueFlag;
    }
    
    /**
     * 校验身份证号
     */
    @PostMapping("/checkIdCardNoUnique")
    @ResponseBody
    public String checkIdCardNoUnique(User user){
    	String uniqueFlag = "0";
    	if(user != null){
    		uniqueFlag = userService.checkIdCardNoUnique(user.getIdCardNo());
    	}
    	return uniqueFlag;
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(User user)
    {
        String uniqueFlag = "0";
        if (user != null)
        {
            uniqueFlag = userService.checkPhoneUnique(user);
        }
        return uniqueFlag;
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(User user)
    {
        String uniqueFlag = "0";
        if (user != null)
        {
            uniqueFlag = userService.checkEmailUnique(user);
        }
        return uniqueFlag;
    }




}

